package net.love5z.web.service;

import net.love5z.web.common.utils.ObjectPropUtils;
import net.love5z.web.dao.UserMapper;
import net.love5z.web.dao.dto.UserDto;
import net.love5z.web.service.bo.CheckUserLoginResult;
import net.love5z.web.service.bo.UserBo;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xmxsuperstar.lib.utils.SHA256Tools;;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public CheckUserLoginResult checkUserLogin(String email, String password) {
        CheckUserLoginResult checkUserLoginResult = new CheckUserLoginResult();
        checkUserLoginResult.setSuccess(false);

        UserDto userDto = userMapper.getUserByEmail(email);

        if (userDto == null) {
            checkUserLoginResult.setErrorMsg("No such User Email!");
        } else {
            UserBo userBo = (UserBo) ObjectPropUtils.createAndCopyProperties(userDto, UserBo.class);

            checkUserLoginResult.setUserBo(userBo);

            String hash = SHA256Tools.hash(email + password + userDto.getPasswordSalt());
            if (StringUtils.equalsIgnoreCase(hash, userDto.getPasswordHash())) {
                checkUserLoginResult.setSuccess(true);
            } else {
                checkUserLoginResult.setErrorMsg("Invalid Email or Password!");
            }
        }

        return checkUserLoginResult;
    }
}
